package controller

import (
	"devops/code"
	"devops/controller/validation"
	"devops/models"
	"devops/pkg/git"
	"devops/pkg/git/git_model"
	"devops/pkg/git/gitea_sdk"
	"devops/pkg/tool"
	"devops/service"
	"encoding/json"
	"fmt"
	"io/ioutil"

	"github.com/gin-gonic/gin"
)

// @Summary 获取所有仓库
// @Tags GIT仓库
// @Produce  json
// @Param	param  query  validation.GetRepos  true      "传入参数"
// @Success 200 {object} data.SuccessGetRepos  			"成功返回"
// @Failure 10000 {object} data.ParamError     			"错误返回"
// @Failure 14001 {object} data.GitClientIsNil     		"错误返回"
// @Router /api/git/user/repos [get]
func GetRepos(c *gin.Context) {
	var param validation.GetRepos
	if err := c.ShouldBind(&param); err != nil {
		ErrorResponse(c, code.PARAMETER_ERR, err.Error())
		return
	}
	client := git.NewGitCli(param.ScmType, param.Token, param.BaseUrl)

	if tool.IsNil(client) {
		ErrorResponse(c, code.CONNECT_FAIL, param.ScmType+"连接失败")
		return
	}
	// 前端不接受 null
	repos, err := client.GetRepos()
	if err != nil {
		ErrorResponse(c, code.CONNECT_FAIL, param.ScmType+" 连接失败")
		return
	}
	if repos == nil {
		repos = make([]git_model.Repo, 0)
	}
	SuccessResponse(c, repos)
}

// @Summary 获取某仓库所有分支
// @Tags GIT仓库
// @Produce  json
// @Param	param  query  validation.GetBranches  true  "传入参数"
// @Success 200 {object} data.SuccessGetBranches  		"成功返回"
// @Failure 10000 {object} data.ParamError     			"错误返回"
// @Failure 14001 {object} data.GitClientIsNil     		"错误返回"
// @Router /api/git/user/repo/branches [get]
func GetBranches(c *gin.Context) {
	var param validation.GetBranches
	if err := c.ShouldBind(&param); err != nil {
		ErrorResponse(c, code.PARAMETER_ERR, err.Error())
		return
	}
	client := git.NewGitCli(param.ScmType, param.Token, param.BaseUrl)
	if client == nil {
		ErrorResponse(c, code.CONNECT_FAIL, param.ScmType+"连接失败")
		return
	}
	SuccessResponse(c, client.GetBranches(param.Owner, param.Repo))
}

func WeebHook(c *gin.Context) {
	b, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	weebHook := gitea_sdk.WeebHook{}
	json.Unmarshal(b, &weebHook)
	ci := models.GetCIByRepoUrl(weebHook.Repository.CloneURL)
	if ci == nil {
		return
	}
	devops := service.NewDevOps()
	devops.PipelineRunByWebHook(ci, weebHook.Commits[0].Message)
}
